package com.xukun.changgou.service.sys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xukun.changgou.common.response.exception.BaseException;
import com.xukun.changgou.service.api.sys.enums.UserOnlineEnum;
import com.xukun.changgou.service.api.sys.enums.UserStatusEnum;
import com.xukun.changgou.service.api.sys.model.ResourceModel;
import com.xukun.changgou.service.api.sys.model.RoleModel;
import com.xukun.changgou.service.api.sys.model.UserModel;
import com.xukun.changgou.service.api.sys.vo.URVo;
import com.xukun.changgou.service.sys.config.CurUser;
import com.xukun.changgou.service.sys.dao.ResourceDao;
import com.xukun.changgou.service.sys.dao.UserDao;
import com.xukun.changgou.service.sys.service.UserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @Author xukun
 * @Date 2021-05-17 13:43
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private CurUser curUser;

    @Autowired
    private UserDao dao;

    @Autowired
    private ResourceDao resourceDao;

    @Override
    public int insert(UserModel record) {
        //用户名检查
        int count = dao.selectCount(new UserModel().setCode(record.getCode()));
        if (count != 0) {
            throw new BaseException("账号重复");
        }
        //密码加密
        String newPass = new BCryptPasswordEncoder().encode(record.getPassword());
        record.setCreateTime(System.currentTimeMillis())
                .setPassword(newPass)
                .setStatus(UserStatusEnum.getValue(UserStatusEnum.正常))
                .setOnlineFlag(UserOnlineEnum.getValue(UserOnlineEnum.下线));
        int result = dao.insertUseGeneratedKeys(record);
        return result;
    }

    @Override
    public int update(UserModel record) {

        if (ObjectUtils.isNotEmpty(record.getPassword())){
            record.setPassword(new BCryptPasswordEncoder().encode(record.getPassword()));
        }

        return dao.updateByPrimaryKeySelective(record.setUpdateTime(System.currentTimeMillis()));
    }

    @Override
    public int deleteById(Integer id) {
        //删除关联关系
        dao.deleteRoleByUser(id);
        return dao.deleteByPrimaryKey(id);
    }

    @Override
    public UserModel queryOneById(Integer id) {
        UserModel userModel = dao.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(userModel)) {
            throw new BaseException("用户不存在");
        }
        return userModel;
    }

    @Override
    public PageInfo<UserModel> queryPageList(Integer pageNum, Integer pageSize, String key) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserModel> list = dao.queryList(key);
        PageInfo<UserModel> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public List<RoleModel> queryRoleListByUser(Integer userId) {
        return dao.queryRoleListByUser(userId);
    }

    @Transactional
    @Override
    public void insertUR(URVo urVo) {
        //先删除之前的关系
        dao.deleteRoleByUser(urVo.getUserId());
        if (ObjectUtils.isNotEmpty(urVo.getRoleList())) {
            dao.insertUserRole(urVo.getUserId(), urVo.getRoleList());
        }
    }

    @Override
    public List<ResourceModel> queryResourceTreeByCurrentUser() {
        Integer currentUserId = curUser.getCurUser().getId();
        List<ResourceModel> list = resourceDao.queryListByParentAndUser(0, currentUserId);
        if (ObjectUtils.isNotEmpty(list)) {
            for (ResourceModel resource : list) {
                List<ResourceModel> children = resourceDao.queryListByParentAndUser(resource.getId(), currentUserId);
                queryTreeList1(children, currentUserId);
                resource.setChildren(children);
            }
        }
        return list;
    }

    @Override
    public List<String> queryPermissionByCurrentUser() {
        Integer currentUserId = curUser.getCurUser().getId();
        List<String> pCodeList = dao.queryPermissionListByUser(currentUserId);
        return pCodeList;
    }

    @Override
    public List<String> queryPermissionListByUser(Integer userId) {
        List<String> pCodeList = dao.queryPermissionListByUser(userId);
        return pCodeList;
    }

    @Override
    public UserModel queryUserByCode(String code) {
        Example example = new Example(UserModel.class);
        example.selectProperties("id", "code", "password", "status");
        example.createCriteria().andEqualTo("code", code);
        return dao.selectOneByExample(example);
    }

    /**
     * 递归查询当前用户资源树
     *
     * @param list        最终要返回的列表
     * @param currentUser 当前用户
     * @return
     */
    private List<ResourceModel> queryTreeList1(List<ResourceModel> list, Integer currentUser) {
        if (ObjectUtils.isNotEmpty(list)) {
            for (ResourceModel resource : list) {
                List<ResourceModel> children = resourceDao.queryListByParentAndUser(resource.getId(), currentUser);
                resource.setChildren(queryTreeList1(children, currentUser));
            }
        }
        return list;
    }
}
